package com.wang.config;

import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import com.google.common.base.Predicates;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author JoyBoy
 */
@Configuration
@EnableWebMvc
@EnableSwagger2
@EnableSwaggerBootstrapUI
public class SwaggerConfig implements WebMvcConfigurer {
    @Value("${swagger.enabled}")
    private boolean enable;

    /*  @Api：修饰整个类，描述Controller的作用
            @ApiOperation：描述一个类的一个方法，或者说一个接口
            @ApiParam：单个参数描述
            @ApiModel：用对象来接收参数
            @ApiProperty：用对象接收参数时，描述对象的一个字段
            @ApiResponse：HTTP响应其中1个描述
            @ApiResponses：HTTP响应整体描述
            @ApiIgnore：使用该注解忽略这个API
            @ApiError ：发生错误返回的信息
            @ApiParamImplicitL：一个请求参数
            @ApiParamsImplicit 多个请求参数
    */
    @Bean
    public Docket getDocket() {
        ParameterBuilder tokenPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<>();
        tokenPar.name("authentication").description("令牌").modelRef(new ModelRef("string"))
                .parameterType("header").required(false).build();
        pars.add(tokenPar.build());

        return new Docket(DocumentationType.SWAGGER_2)
                // 通过.select()方法，去配置扫描接口,RequestHandlerSelectors配置如何扫描接口
                .select()
                // any:扫描所有，项目中的所有接口都会被扫描到
                //.apis(RequestHandlerSelectors.any())
                // 根据包路径扫描接口
                .apis(Predicates.or(
                        RequestHandlerSelectors.basePackage("com.wang.controller"),
                        RequestHandlerSelectors.basePackage("com.wang.config.security")
                ))
                // 配置如何通过path过滤,即这里只扫描请求以/td开头的接口
//                .paths(PathSelectors.any())
                .paths(PathSelectors.ant("/td/**"))
                .build()
                .globalOperationParameters(pars)
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts())
                //配置是否启用Swagger，如果是false，在浏览器将无法访问
                .enable(enable)
                // Docket 实例关联上 apiInfo()
                .apiInfo(getInfo());
    }

    /**
     * 对API文档进行全局配置
     */
    private ApiInfo getInfo() {
        return new ApiInfoBuilder()
                // 标题
                .title("TongueDiagnosisSystem")
                // 描述
                .description("智慧舌诊系统")
                // 版本
                .version("v1.0")
                // 组织链接
                .termsOfServiceUrl("http://www.ccsubranch1204.com")
                // 许可
                .license("小树枝团队版权所有")
                .description("小树枝帮助文档")
                // 联系人信息
                .contact(
                        new Contact(
                                "branch",
                                "https://www.ccsubranch1204.com",
                                "848144800@qq.com"))
                //许可链接
                .licenseUrl("https://www.ccsubranch1204.com")
                .extensions(Collections.emptyList())
                .build();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations(
                "classpath:/static/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        registry.addResourceHandler("doc.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");
    }

    private List<ApiKey> securitySchemes() {
        List<ApiKey> apiKeyList = new ArrayList<>();
        apiKeyList.add(new ApiKey("authentication", "authentication", "header"));
        return apiKeyList;
    }

    private List<SecurityContext> securityContexts() {
        List<SecurityContext> securityContexts = new ArrayList<>();
        securityContexts.add(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
//                        表示所有带有user的接口路径
                        .forPaths(PathSelectors.regex("^(?!user).*$"))
                        .forPaths(PathSelectors.any())
                        .build());
        return securityContexts;
    }

    List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        List<SecurityReference> securityReferences = new ArrayList<>();
        securityReferences.add(new SecurityReference("authentication", authorizationScopes));
        return securityReferences;
    }
}
